package com.heima.schedule.service;

import com.alibaba.fastjson.JSON;
import com.heima.common.redies.CacheService;
import com.heima.model.schedule.dto.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.dc.pr.PRError;

import javax.xml.ws.ServiceMode;
import java.util.Date;

/**
 * @anthor hhp
 * @date 2022/7/18 18:01
 */

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoService taskinfoService;

    @Autowired
    private TaskinfoLogsService taskinfoLogsService;

    @Autowired
    private CacheService cacheService;


    @Override
    public Long addTask(Task task) {
        //0检验task是否为空

        if (task == null) {
            log.warn("入参不能为空");
            return null;
        }
        //1.插入taskinfo表
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

        boolean taskInfoResult = taskinfoService.save(taskinfo);
        if (!taskInfoResult) {

            log.warn("任务插入失败");

            return null;
        }
        //2.插入taskinlog表
        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, logs);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        logs.setStatus(0);

        boolean logsResult = taskinfoLogsService.save(logs);
        if (!logsResult) {

            log.warn("日志插入失败");
            throw new RuntimeException("日志插入失败");
        }
        //3.判断任务执行时间是否小于当前时间
        //任务执行时间
        long executeTime = task.getExecuteTime();
        //当前时间
        long currentTime = System.currentTimeMillis();
        if (executeTime <= currentTime) {
            //加入到当前队列
            cacheService.lLeftPush("TOPIC", JSON.toJSONString(task));
        }

        //4.判断任务执行时间是否小于五分钟
        long futureTime = currentTime + (5 * 60 * 1000);
        if (executeTime <= futureTime) {
            cacheService.zAdd("FUTURE",JSON.toJSONString(task),executeTime);
        }
        //5.返回任务id
        return taskinfo.getTaskId();

    }
}


